<?php
/*
 * Copyright 2009 YoYo Systems, Inc.
 *
 */

class AppConf
{
  protected $conf;

  public function __construct($filename)
  {
    $this->conf = self::load($filename); 
  }

  public function add($filename)
  {
    $newConf = self::load($filename);
    if($newConf == null) $newConf = array();

    foreach ($newConf as $newSecName => $newSecArr) {
      
      if ($this->conf[$newSecName]) { // have same section between old & new conf

        // replace old item/value pair
        foreach ($newSecArr as $newItemName => $newItemValue) {
          $this->conf[$newSecName][$newItemName] = $newItemValue;
        }
      } else {
        $this->conf[$newSecName] = $newSecArr;
      }
    }
  }

  public function getConf()
  {
    return $this->conf;
  }

  /*
   * load an INI file by the given file path
   * @return: 2-dimension array
   *          or empty array if file is not exists.
   */
  protected static function load($filename)
  {
    if (!file_exists($filename)) {
      return array();
    }

    $iniSetting = array();
    $lineArr = file($filename);

		foreach ($lineArr as $line) {
			$dataLine = trim($line);
      $firstChar = substr($dataLine, 0, 1);

			if ($firstChar != ';' && $dataLine != '') {
				if ($firstChar == '[' && substr($dataLine, -1, 1) == ']') {
					$sectionName = preg_replace('/[\[\]]/', '', $dataLine);
				} else {
					$delimiter = strpos($dataLine, '=');

					if ($delimiter > 0) {
						$key = strtolower(trim(substr($dataLine, 0, $delimiter)));
						$value = trim(substr($dataLine, $delimiter + 1));

						if (substr($value, 0, 1) == '"' && substr($value, -1) == '"') {
							$value = substr($value, 1, -1);
						}

						$iniSetting[$sectionName][$key]=stripcslashes($value);
					} else {
						if (!isset($sectionName)) {
							$sectionName = '';
						}

						$iniSetting[$sectionName][strtolower(trim($dataLine))]='';
					}
				}
			}
		}

		return $iniSetting;
  }

  public function confValue($sectionName, $itemName)
  {
    return $this->conf[$sectionName][$itemName];
  }

  public function confGroup($sectionName) {
    return $this->conf[$sectionName];
  }
}


?>
